/**********************
**intellistrip.inc
**Date Created: 4/13/2009
**Copyright 2009 Tomorrow Tech Industries
**Contact: RPITomorrowTech@gmail.com
**********************/

#ifndef INTELLISTRIP_SERIAL_H
#define INTELLISTRIP_SERIAL_H

#include <string>
#include "intellistrip.h"

using namespace std;

#ifndef FALSE
#define FALSE 0
#endif
#ifndef TRUE
#define TRUE 1
#endif

#ifdef NDEBUG 
  #define printf_debug(...)
#else /* ifdef NDEBUG */
  extern int g_verbose;
  #define printf_debug(format, ...) if( g_verbose ) { printf(format, ## __VA_ARGS__); }
#endif /* ifndef NDEBUG */


class IntellistripSerial
{
/***********
Functions
***********/
public:
	/**********
	Initialization
	**********/
	IntellistripSerial();
	~IntellistripSerial();
	//Default to 38400, 8N1
	ttRC init(string serialDevice = "/dev/ttyUSB0", 
									long baudRate = 38400, 
									int dataBits = 8,
									int stopBits = 1, 
									//TODO: find a define for this
									//Evidently this is none
									int parity = 0, 
									string password = "intellimation");
	
	/**********
	public functions
	**********/
	ttRC getIntellistripInformation(string &vendorName, string &modelNumber, 
									string &modelVersion, string &serialNumber,
									int &numberPorts, int &state);	
	ttRC setPortPower(int port, int powerLevel);	
	ttRC getPortPower(int port, int &powerLevel);
	ttRC setPassword(string newPassword);

protected:
	ttRC readChar(ttUI8_t *charRead);
	ttRC readBuffer(ttUI8_t *buffer, int bufferSize);
	ttRC writeChar(ttUI8_t toWrite);
	ttRC writeBuffer(const ttUI8_t *buffer, int bufferSize);

	ttRC sendRequest(const struct IntellistripSerialRequest *request);
	ttRC recieveResponse(struct IntellistripSerialResponse **responseRet);

/***********
Static functions
***********/
public:
	static string getLastError();
	static void clearLastError();

protected:
	static void setLastError(const char *error, ...);

private:
	//This function is never called by this code, only by function pointer callback
	static void signalHandlerIO(int status);

/***********
Member variables
***********/
protected:
	//File descriptor to our serial port
	int serialFd;
	//Serial device (ex: /dev/ttyUSB0 or /dev/S0)
	string serialDevice;
	//Password intellistrip needs to perform actions
	string password;

	//8051 dev boards uses 38400, 8N1
	//Original code had somehting about this being used as an interrupt handler, but it looks like it never was
	int active;
	//Speed of connection
	long baudRate;
	//How many bits per byte
	int dataBits;
	//Number of stop bits
	int stopBits;
	//byte parity
	int parity;

	//place for old and new port settings for serial port
	struct termios oldtio, newtio;       
	
private:
	static string lastError;

	//TRUE while no signal received
	//Unfortunatly, cannot currently distinguish between callbacks, so this must be a static wakeup
	static int waitFlag;
};

#endif
